package srv

import (
	dbModel "back/entity/model"
	"back/entity/nailEntity"
	"back/entity/nailRepo"
	requset "back/router/request"
	"github.com/redis/go-redis/v9"
	"gorm.io/gen"
	"utilx/dbx/cache"
)

type NailService struct {
	Repo   nailRepo.NailRepo
	bucket cache.RedisBucket
	redis  *redis.Client
}

func NewServiceRecord(repo nailRepo.NailRepo, bucket cache.RedisBucket) NailService {
	client := bucket.GetClient(1)
	return NailService{repo, bucket, client}
}
func (c NailService) SearchById(id int64) (*nailEntity.NailService, error) {
	return c.Repo.NailService.Where(nailRepo.NailService.ID.Eq(id)).First()
}
func (c NailService) SearchBy(rec requset.SearchWithPage[nailEntity.NailService]) (any, error) {
	do := c.Repo.NailService.Debug()
	do = do.Where(
		nailRepo.NailService.ProjectName.Like(rec.Data.ProjectName+"%"),
		nailRepo.NailService.EmployeeName.Like(rec.Data.EmployeeName+"%"),
	).Order(nailRepo.NailService.CreatedAt.Desc())
	byPage, i, err := do.FindByPage(int(rec.PageInfo.PageSize)*int(rec.PageInfo.Page-1), int(rec.PageInfo.PageSize))
	return requset.PageResult[nailEntity.NailService]{
		Items: byPage,
		Total: i,
	}, err
}
func (c NailService) DelById(id int64) (gen.ResultInfo, error) {
	return c.Repo.NailService.Where(nailRepo.NailService.ID.Eq(id)).Delete()
}
func (c NailService) UpdateById(rec nailEntity.NailService) error {

	return c.Repo.NailService.Where(nailRepo.NailService.ID.Eq(rec.ID)).Save(&rec)
}
func (c NailService) UpdateBy(rec requset.UpdateBy[nailEntity.NailService, nailEntity.NailService]) error {

	return c.Repo.NailService.Where(nailRepo.NailService.ID.Eq(rec.Where.ID)).Save(&rec.Target)
}
func (c NailService) CacheSearchById(force bool, id int64) (any, error) {
	return cache.GetAop[nailEntity.NailService](force, c.redis, dbModel.RedisKey(dbModel.TypeCheckout, id), func() (any, error) {
		return c.SearchById(id)
	})
}
func (c NailService) CacheSearchBy(force bool, rec requset.SearchWithPage[nailEntity.NailService]) (any, error) {
	return cache.GetAop[requset.PageResult[nailEntity.NailService]](force, c.redis, dbModel.RedisKey(dbModel.TypeCheckout, rec), func() (any, error) {
		return c.SearchBy(rec)
	})
}

// Create 进行单次服务
func (c NailService) Create(rec *nailEntity.NailService) error {
	var totalAmount int32 = 0
	for _, service := range rec.Services { //消耗的产品
		c.Repo.NailProduct.Where(nailRepo.NailProject.ID.Eq(service.ID)).UpdateColumnSimple(nailRepo.NailProduct.Quantity.Add(-service.Quantity))
		totalAmount += service.Quantity * service.UnitPrice
		// 库存记录
		c.Repo.NailStorageRecord.Create(&nailEntity.NailStorageRecord{
			ProductName: service.Name,
			UnitPrice:   service.UnitPrice,
			Quantity:    -service.Quantity,
		})
	}
	rec.Amount = totalAmount
	return c.Repo.NailService.Create(rec)
}
